package org.jeecg.modules.xl.aftersale.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.xl.aftersale.dto.AftersaleAuditDto;
import org.jeecg.modules.xl.aftersale.entity.XlCustomerAftersale;
import org.jeecg.modules.xl.aftersale.entity.XlCustomerAftersaleDetail;
import org.jeecg.modules.xl.aftersale.mapper.XlCustomerAftersaleDetailMapper;
import org.jeecg.modules.xl.aftersale.mapper.XlCustomerAftersaleMapper;
import org.jeecg.modules.xl.aftersale.service.IXlCustomerAftersaleDetailService;
import org.jeecg.modules.xl.aftersale.service.IXlCustomerAftersaleService;
import org.jeecg.modules.xl.order.utils.DictUtils;
import org.jeecg.modules.xl.order.utils.StrCommonUtil;
import org.jeecg.modules.xl.store.entity.XlCustomerStoreInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 售后单
 * @Author: jeecg-boot
 * @Date: 2024-11-03
 * @Version: V1.0
 */
@Service
public class XlCustomerAftersaleServiceImpl extends ServiceImpl<XlCustomerAftersaleMapper, XlCustomerAftersale> implements IXlCustomerAftersaleService {

    @Resource
    private XlCustomerAftersaleMapper xlCustomerAftersaleMapper;
    @Resource
    private XlCustomerAftersaleDetailMapper xlCustomerAftersaleDetailMapper;

    @Autowired
    private IXlCustomerAftersaleDetailService xlCustomerAftersaleDetailService;
    @Autowired
    private DictUtils dictUtils;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> saveMain(XlCustomerAftersale xlCustomerAftersale, List<XlCustomerAftersaleDetail> xlCustomerAftersaleDetailList) {
//        if (this.count(Wrappers.lambdaQuery(XlCustomerAftersale.class)
//                .eq(XlCustomerAftersale::getOrderCode, xlCustomerAftersale.getOrderCode())
//        ) > 0) {
//            //throw new JeecgBootException("该订单已发起售后申请！！");
//        }
        String pre = "SHD"+new SimpleDateFormat("yyMMdd").format(new Date());	//编码前缀
        String suffix = RandomUtil.randomNumbers(4);
        xlCustomerAftersale.setWorkorder(pre + suffix);    //编号生成;
        xlCustomerAftersale.setWoStatus(dictUtils.getDictValue("audit_state","待审核"));//审核状态
        //2024-11-29 19:27:29 取消了售后订单的售后原因，为了数据完整性，需要设置一个默认值
        xlCustomerAftersale.setRenson("1");
        xlCustomerAftersale.setCreateBy(null);
        xlCustomerAftersale.setCreateTime(null);
        xlCustomerAftersale.setUpdateBy(null);
        xlCustomerAftersale.setUpdateTime(null);
        Double totalNum = 0.0;//售后商品总数量
        Integer detailNum = 0;//售后商品种数
        Double totalAmount = 0.0; //售后总金额
        //xlCustomerAftersaleMapper.insert(xlCustomerAftersale);
        if (xlCustomerAftersaleDetailList != null && xlCustomerAftersaleDetailList.size() > 0) {
            for (XlCustomerAftersaleDetail entity : xlCustomerAftersaleDetailList) {
                //如果没有设置售后数量，就自动跳过
                if (ObjectUtil.isEmpty(entity.getAftersaleQuantity())  || entity.getAftersaleQuantity().compareTo(BigDecimal.ZERO) == 0) {
                    continue;
                }
                //如果订单的某个品发起过售后，则无法提交，提醒找管理员删除，避免状态不一致。
                QueryWrapper<XlCustomerAftersaleDetail> xlCustomerAftersaleDetailQueryWrapper = new QueryWrapper<>();
                xlCustomerAftersaleDetailQueryWrapper.eq("order_code",entity.getOrderCode());
                xlCustomerAftersaleDetailQueryWrapper.eq("upc_code",entity.getUpcCode());
                XlCustomerAftersaleDetail ex = xlCustomerAftersaleDetailMapper.selectOne(xlCustomerAftersaleDetailQueryWrapper);
                if(ObjectUtil.isNotEmpty(ex)){
                    String msg = StrUtil.format("订单：{}的商品{}已经创建了售后单{},通过商品无法发起两次售后,请核实",entity.getOrderCode(),entity.getUpcCode(),ex.getWorkorder());
                    //判断通过的部分明细已经插入成功了，需要手动回滚。
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return Result.error(msg);
                }
                //外键设置
                entity.setWorkorder(xlCustomerAftersale.getWorkorder());
                //如果明细上的售后原因为空，则赋值总的原因
                if(ObjectUtil.isEmpty(entity.getReason())){
                    entity.setReason(xlCustomerAftersale.getRenson());
                }
                entity.setWoStatus(dictUtils.getDictValue("audit_state","待审核"));
                entity.setCreateBy(null);
                entity.setCreateTime(null);
                entity.setUpdateBy(null);
                entity.setUpdateTime(null);
                //如果售后原因没有，就
                xlCustomerAftersaleDetailMapper.insert(entity);

                totalNum = totalNum + entity.getAftersaleQuantity().doubleValue();
                totalAmount = totalAmount + entity.getAftersaleAmount().doubleValue();
                detailNum = detailNum + 1;
            }

        }

        xlCustomerAftersale.setTotalNum(totalNum);
        xlCustomerAftersale.setDetailNum(detailNum);
        xlCustomerAftersale.setTotalAmount(totalAmount);
        //xlCustomerAftersaleMapper.updateById(xlCustomerAftersale);
        xlCustomerAftersaleMapper.insert(xlCustomerAftersale);
        return Result.OK("售后单发起成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMain(XlCustomerAftersale xlCustomerAftersale, List<XlCustomerAftersaleDetail> xlCustomerAftersaleDetailList) {
        xlCustomerAftersaleMapper.updateById(xlCustomerAftersale);

        //1.先删除子表数据
        xlCustomerAftersaleDetailMapper.deleteByMainId(xlCustomerAftersale.getId()+"");

        //2.子表数据重新插入
        Double totalNum = 0.0;//售后商品总数量
        Integer detailNum = 0;//售后商品种数
        Double totalAmount = 0.0; //售后总金额
        if (xlCustomerAftersaleDetailList != null && xlCustomerAftersaleDetailList.size() > 0) {
            for (XlCustomerAftersaleDetail entity : xlCustomerAftersaleDetailList) {
                //如果没有指定数量
                if (entity.getAftersaleQuantity() == null || entity.getAftersaleQuantity().compareTo(BigDecimal.ZERO) == 0) {
                    continue;
                }
                //外键设置
                entity.setWorkorder(xlCustomerAftersale.getWorkorder());
                xlCustomerAftersaleDetailMapper.insert(entity);

                totalNum = totalNum + entity.getAftersaleQuantity().doubleValue();
                totalAmount = totalAmount + entity.getAftersaleQuantity().doubleValue();
                detailNum = detailNum + 1;
            }
        }

        xlCustomerAftersale.setTotalNum(totalNum);
        xlCustomerAftersale.setDetailNum(detailNum);
        xlCustomerAftersale.setTotalAmount(totalAmount);
        xlCustomerAftersaleMapper.updateById(xlCustomerAftersale);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMain(String id) {
        xlCustomerAftersaleDetailMapper.deleteByMainId(id);
        xlCustomerAftersaleMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            xlCustomerAftersaleDetailMapper.deleteByMainId(id.toString());
            xlCustomerAftersaleMapper.deleteById(id);
        }
    }

    @Override
    public Result<String> audit(AftersaleAuditDto dto) {
        List<String> idList = Lists.newArrayList();
        idList.addAll(Arrays.asList(dto.getId().split(",")));
        List<XlCustomerAftersale> list = this.listByIds(idList);
        if (list.size() == idList.size()) {
            //筛选判断是否有已审核的数据
            String codes = list.stream().filter(f -> f.getWoStatus() != null && (dictUtils.getDictValue("audit_state", "审核通过").equals(f.getWoStatus())
                    || dictUtils.getDictValue("audit_state", "审核不通过").equals(f.getWoStatus()))
            ).map(m -> m.getWorkorder()).collect(Collectors.joining(","));

            //判断是否已审核
            if (ObjectUtil.isNotEmpty(codes)) {
                return  Result.error("售后单【" + codes + "]已审核,不能操作！");
            }
        } else {
            return  Result.error("选择的数据中有无效数据,请刷新后重新操作");
        }

        //先更新明细，避免明细错误，导致行项目更新
        //更新明细表里的状态字段
        List<String> woorders = list.stream().map(m -> m.getWorkorder()).collect(Collectors.toList());
        UpdateWrapper<XlCustomerAftersaleDetail> detailUpdateWrapper = new UpdateWrapper<>();
        detailUpdateWrapper.lambda().set(XlCustomerAftersaleDetail::getWoStatus, dto.getWoStatus())
                .in(XlCustomerAftersaleDetail::getWorkorder, woorders);

        //更新明细表里的状态修改为 已审核（审核通过或作不通过）
        try {
            xlCustomerAftersaleDetailService.update(detailUpdateWrapper);
        } catch (DuplicateKeyException e) {
            return  Result.error("已经存在审核的记录，请联系管理员处理！");
        }


        UpdateWrapper<XlCustomerAftersale> wrapper = new UpdateWrapper<>();
        wrapper.setSql(" wo_note = concat('审批意见:',{0},';',wo_note) ", dto.getWoNote())
                .lambda().set(XlCustomerAftersale::getWoStatus, dto.getWoStatus())
                .in(XlCustomerAftersale::getId, idList);

        //修改为 已审核（审核通过或作不通过）
        this.update(wrapper);
        return Result.OK("审核成功！");
    }

}
